/*
 * @Author: 刘凯欣
 * @Date: 2025-11-07 09:14:57
 * @LastEditors: happyBoomL
 * @LastEditTime: 2025-11-08 17:40:50
 * @Description: 
 */
const express = require('express');
const router = express.Router();
const {
    Article
} = require('../../models')

// Op是Sequelize的运算符，用于构建查询条件
const {
    Op
} = require('sequelize')


const {
    NotFoundError,
    success,failure
} = require('../../utils/response')



/**
 * @description: 查询文章列表
 * @return {*}
 */
router.get("/", async function (req, res) {
    try {
        const query = req.query;
        // 定义查询条件
        const conditions = {
            // 这里在数组里又嵌套了数组。这就说明，排序可能不止按一个字段来排序，也可能同时按多个字段来排序。
            order: [
                ['id', 'desc']
            ]
        }

        // SELECT *
        // FROM `Articles`
        // WHERE title LIKE '%文章10%'
        // 增加搜索条件
        if (query.title) {
            conditions.where = {
                title: {
                    [Op.like]: `%${query.title}%`
                }
            }
        }
        // 增加 分页功能

        // 原始sql
        // SELECT *
        // FROM `Articles`
        // LIMIT 0,10

        // 处理用户传入的可能是负数的问题  || 1 表示如果用户没有传入page和pageSize，则默认为1和10
        const page = Math.abs(Number(query.page)) || 1;
        const pageSize = Math.abs(Number(query.pageSize)) || 10;
        if (page && pageSize) {
            conditions.offset = (page - 1) * pageSize;
            conditions.limit = pageSize;
        }

        // const articles = await Article.findAll(conditions);

        const articles = await Article.findAndCountAll(conditions);
        success(res, "成功", {
            list: articles.rows,
            pagination: {
                total: articles.count,
                page: page,
                pageSize: pageSize
            }
        }, 200);
    } catch (error) {
        failure(res,error);
    }
});

/**
 * @description: 文章详情接口
 * @return {*}
 */
router.get("/:id", async function (req, res) {
    try {
        const {
            id
        } = req.params;

        // 调用公用获取 文章详情的方法
        const article = await getArticle(req);
        success(res, "成功", article, 200)
    } catch (error) {
        failure(res,error);
    }
})


/**
 * @description: 添加文章接口
 * @return {*}
 */
router.post("/", async function (req, res) {
    try {
        const article = await Article.create(FilterBody(req))
        res.status(201).json({
            status: true,
            message: "成功",
            data: article
        })
        success(res, "成功", article, 201);
    } catch (error) {
        failure(res,error);
    }
})
/**
 * 更新文章
 * PUT /admin/articles/:id
 */
router.put('/:id', async function (req, res) {
    try {
        // 调用公用
        const article = await getArticle(req);
        await article.update(req.body);
        success(res, "更新文章成功。", article, 200)

    } catch (error) {
        failure(res,error);
    }
});

/**
 * @description: 删除文章接口
 * @return {*}
 */

router.delete('/:id', async function (req, res) {
    try {
        // 调用公用
        const article = await getArticle(req);
        await article.destroy();
        success(res, '删除文章成功。');
    } catch (error) {
        failure(res,error);
    }
})



/**
 * @description: 白名单过滤
 * @return {*}
 */

function FilterBody(req) {
    return {
        title: req.body.title,
        content: req.body.content
    }
}

/**
 * @description: 公用获取文章内容的函数
 * @return {*}
 */

async function getArticle(req) {
    const {
        id
    } = req.params;
    const article = await Article.findByPk(id);
    if (article) {
        return article;
    } else {
        throw new NotFoundError(`文章id为${id}的文章不存在`);
    }
}


module.exports = router;